// utils/mock-api.js
// 模拟API响应，用于开发和测试

const { showSuccess, generateRandomString } = require('./util.js')

/**
 * 模拟API响应延迟
 */
const simulateNetworkDelay = (min = 500, max = 1500) => {
  const delay = Math.random() * (max - min) + min
  return new Promise(resolve => setTimeout(resolve, delay))
}

/**
 * 生成模拟用户数据
 */
const generateMockUser = () => {
  const nicknames = ['青鸟笺小助手', '测试用户', '开发者', '小明', '小红', '小华']
  const randomNickname = nicknames[Math.floor(Math.random() * nicknames.length)]
  
  return {
    openid: `mock_openid_${generateRandomString(16)}`,
    nickname: randomNickname,
    gender: Math.floor(Math.random() * 2) + 1, // 1:男, 2:女
    language: 'zh_CN',
    city: '北京',
    province: '北京',
    country: '中国'
  }
}

/**
 * 生成模拟用户档案数据
 */
const generateMockUserProfile = (index = 0) => {
  const names = ['张伟', '李娜', '王强', '刘敏', '陈杰', '杨丽', '赵磊', '孙静', '周涛', '吴雪', '郑华', '王芳', '李明', '张丽', '刘伟'];
  const occupations = ['医生', '教师', '工程师', '律师', '护士', '公务员', '设计师', '会计师', '销售经理', '程序员'];
  const educations = ['本科', '硕士', '博士', '大专', '高中'];
  const cities = ['上海', '杭州', '合肥', '北京', '南京', '芜湖'];
  const maritalStatuses = ['未婚', '离异', '丧偶'];
  
  const gender = Math.random() > 0.5 ? '男' : '女';
  const age = 22 + Math.floor(Math.random() * 18); // 22-40岁
  const height = gender === '男' ? 165 + Math.floor(Math.random() * 25) : 155 + Math.floor(Math.random() * 25); // 男165-190, 女155-180
  const weight = gender === '男' ? 120 + Math.floor(Math.random() * 60) : 90 + Math.floor(Math.random() * 50); // 男120-180斤, 女90-140斤
  
  return {
    userNum: 10001 + index,
    name: names[index % names.length],
    gender: gender,
    height: height,
    weight: weight,
    age: age,
    maritalStatus: maritalStatuses[Math.floor(Math.random() * maritalStatuses.length)],
    assets: {
      annualIncome: 10 + Math.floor(Math.random() * 90), // 10-100万
      car: Math.random() > 0.3 ? '有车' : '无车',
      house: Math.random() > 0.4 ? '有房' : '无房'
    },
    education: educations[Math.floor(Math.random() * educations.length)],
    occupation: occupations[Math.floor(Math.random() * occupations.length)],
    isPartyMember: Math.random() > 0.7, // 30%概率是党员
    hometown: cities[Math.floor(Math.random() * cities.length)],
    currentResidence: cities[Math.floor(Math.random() * cities.length)],
    birthDate: `${1984 + Math.floor(Math.random() * 18)}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
    chineseZodiac: ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'][Math.floor(Math.random() * 12)],
    bmiDesc: height && weight ? (weight / 2 / Math.pow(height / 100, 2) < 24 ? '正常' : '偏重') : '正常'
  };
};

/**
 * 模拟API响应数据
 */
const mockApiResponses = {
  // 微信登录
  '/api/auth/wechat-login': {
    code: 0,
    message: '登录成功',
    data: {
      token: `mock_jwt_token_${Date.now()}`,
      refreshToken: `mock_refresh_token_${Date.now()}`,
      expiresIn: 3600, // 1小时
      userInfo: generateMockUser(),
      userProfile: {
        userId: `user_${generateRandomString(8)}`,
        nickname: '新用户',
        avatarConfig: null, // 新用户没有头像配置
        isNewUser: true,
        isRealNameVerified: false,
        isEducationVerified: false,
        isWorkVerified: false,
        profileCompletion: 20
      }
    }
  },
  
  // Token验证
  '/api/auth/verify-token': {
    code: 0,
    message: 'Token有效',
    data: {
      userProfile: {
        userId: 'user_12345',
        nickname: '测试用户',
        avatarConfig: {
          face: 'face1',
          hair: 'hair2',
          outfit: 'outfit1',
          accessory: 'glasses'
        },
        isNewUser: false,
        profileCompletion: 85
      }
    }
  },
  
  // 刷新Token
  '/api/auth/refresh-token': {
    code: 0,
    message: 'Token刷新成功',
    data: {
      token: `new_mock_jwt_token_${Date.now()}`,
      refreshToken: `new_mock_refresh_token_${Date.now()}`,
      expiresIn: 3600
    }
  },
  
  // 手机验证码发送
  '/api/auth/send-sms': {
    code: 0,
    message: '验证码发送成功',
    data: {
      success: true,
      mockCode: '123456' // 开发模式下显示验证码
    }
  },
  
  // 手机号验证登录
  '/api/auth/phone-verify': {
    code: 0,
    message: '验证成功',
    data: {
      token: `phone_jwt_token_${Date.now()}`,
      refreshToken: `phone_refresh_token_${Date.now()}`,
      expiresIn: 3600,
      userInfo: {
        phone: '138****1234',
        nickname: '手机用户'
      },
      userProfile: {
        userId: `phone_user_${generateRandomString(8)}`,
        nickname: '手机用户',
        avatarConfig: null,
        isNewUser: true
      }
    }
  },

  // 用户档案查询
  '/matchmaking/userprofile/query': {
    code: 0,
    message: '查询成功',
    data: {
      userprofileList: Array.from({ length: 20 }, (_, index) => generateMockUserProfile(index)),
      totalNum: 156 // 模拟总数
    }
  },

  // 用户详细信息查询
  '/matchmaking/userprofile/allInfo': {
    code: 0,
    message: '查询成功',
    data: {
      userInfoList: Array.from({ length: 3 }, (_, index) => {
        const baseProfile = generateMockUserProfile(index);
        return {
          ...baseProfile,
          // 添加详细信息
          personalStatement: '希望找到一个志同道合的人，一起走过人生的每一个阶段。',
          interests: ['运动健身', '音乐', '旅行'],
          familyMembers: {
            familyType: '三口之家',
            fatherDetail: { age: 55, desc: '退休教师' },
            motherDetail: { age: 52, desc: '医院护士' },
            otherDetail: []
          },
          // 择偶要求
          ageRange: { minAge: 25, maxAge: 35 },
          minHeight: baseProfile.gender === '男' ? 0 : 170,
          maxWeight: baseProfile.gender === '男' ? 140 : 120,
          minIncome: 15,
          occupationRequire: '不限',
          hometownPreference: ['上海', '杭州'],
          currentResidencePreference: ['上海', '杭州', '北京'],
          personalityRequire: '温柔体贴',
          otherRequire: '希望对方有责任心'
        };
      })
    }
  }
}

/**
 * 模拟网络请求
 */
const mockRequest = async (url, method = 'GET', data = {}) => {
  console.log(`🔧 Mock API Request: ${method} ${url}`, data)
  
  // 模拟网络延迟
  await simulateNetworkDelay(800, 1200)
  
  // 随机模拟网络错误 (5% 概率)
  if (Math.random() < 0.05) {
    throw new Error('Mock network error - 模拟网络错误')
  }
  
  // 获取模拟响应
  const response = mockApiResponses[url]
  
  if (!response) {
    // 未配置的API返回默认成功响应
    return {
      code: 0,
      message: '操作成功',
      data: {
        success: true,
        mockData: true
      }
    }
  }
  
  // 对于某些特殊情况的处理
  if (url === '/api/auth/wechat-login') {
    // 每次生成新的用户数据
    const newResponse = {
      ...response,
      data: {
        ...response.data,
        userInfo: generateMockUser(),
        token: `mock_jwt_token_${Date.now()}`,
        refreshToken: `mock_refresh_token_${Date.now()}`
      }
    }
    return newResponse
  }
  
  // 模拟手机验证码校验
  if (url === '/api/auth/phone-verify' && data.verificationCode !== '123456') {
    return {
      code: 1001,
      message: '验证码错误',
      data: null
    }
  }

  // 处理用户档案查询
  if (url === '/matchmaking/userprofile/query') {
    const { pageNum = 1, pageSize = 20, gender, ageRange, heightRange, weightRange, educationRange, incomeRange, occupation, parentsHasPension } = data;
    
    // 生成符合筛选条件的用户数据
    let allUsers = Array.from({ length: 156 }, (_, index) => generateMockUserProfile(index));
    
    // 应用筛选条件
    let filteredUsers = allUsers.filter(user => {
      // 性别筛选
      if (gender && user.gender !== gender) return false;
      
      // 年龄筛选
      if (ageRange) {
        if (ageRange.minAge && user.age < ageRange.minAge) return false;
        if (ageRange.maxAge && user.age > ageRange.maxAge) return false;
      }
      
      // 身高筛选
      if (heightRange) {
        if (heightRange.minHeight && user.height < heightRange.minHeight) return false;
        if (heightRange.maxHeight && user.height > heightRange.maxHeight) return false;
      }
      
      // 体重筛选
      if (weightRange) {
        if (weightRange.minWeight && user.weight < weightRange.minWeight) return false;
        if (weightRange.maxWeight && user.weight > weightRange.maxWeight) return false;
      }
      
      // 学历筛选
      if (educationRange && educationRange.minEducation) {
        const educationLevels = ['高中', '大专', '本科', '硕士', '博士'];
        const userLevel = educationLevels.indexOf(user.education);
        const minLevel = educationLevels.indexOf(educationRange.minEducation);
        if (userLevel < minLevel) return false;
      }
      
      // 收入筛选
      if (incomeRange && incomeRange.minIncome) {
        if (user.assets.annualIncome < incomeRange.minIncome) return false;
      }
      
      // 职业筛选
      if (occupation && !user.occupation.includes(occupation)) return false;
      
      // 父母退休金筛选
      if (parentsHasPension !== null && parentsHasPension !== undefined) {
        // 模拟父母退休金状态（随机）
        const hasParentsPension = Math.random() > 0.4; // 60%有退休金
        if (parentsHasPension !== hasParentsPension) return false;
      }
      
      return true;
    });
    
    // 分页处理
    const startIndex = (pageNum - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedUsers = filteredUsers.slice(startIndex, endIndex);
    
    console.log(`🔧 Mock API: 筛选后用户总数 ${filteredUsers.length}, 返回第${pageNum}页 ${paginatedUsers.length} 个用户`);
    
    return {
      code: 0,
      message: '查询成功',
      data: {
        userprofileList: paginatedUsers,
        totalNum: filteredUsers.length
      }
    };
  }

  // 处理用户详细信息查询
  if (url === '/matchmaking/userprofile/allInfo') {
    const { userNumList = [] } = data;
    
    const userInfoList = userNumList.map(userNum => {
      const baseProfile = generateMockUserProfile(userNum - 10001);
      return {
        ...baseProfile,
        userNum: userNum,
        // 添加详细信息
        personalStatement: '希望找到一个志同道合的人，一起走过人生的每一个阶段。',
        interests: ['运动健身', '音乐', '旅行'],
        familyMembers: {
          familyType: '三口之家',
          fatherDetail: { age: 55, desc: '退休教师' },
          motherDetail: { age: 52, desc: '医院护士' },
          otherDetail: []
        },
        // 择偶要求
        ageRange: { minAge: 25, maxAge: 35 },
        minHeight: baseProfile.gender === '男' ? 0 : 170,
        maxWeight: baseProfile.gender === '男' ? 140 : 120,
        minIncome: 15,
        occupationRequire: '不限',
        hometownPreference: ['上海', '杭州'],
        currentResidencePreference: ['上海', '杭州', '北京'],
        personalityRequire: '温柔体贴',
        otherRequire: '希望对方有责任心'
      };
    });
    
    return {
      code: 0,
      message: '查询成功',
      data: {
        userInfoList: userInfoList
      }
    };
  }
  
  return response
}

/**
 * 模拟文件上传
 */
const mockUpload = async (filePath, options = {}) => {
  console.log('🔧 Mock File Upload:', filePath, options)
  
  await simulateNetworkDelay(1000, 2000)
  
  return {
    code: 0,
    message: '上传成功',
    data: {
      url: `https://mock-cdn.example.com/files/${generateRandomString(16)}.jpg`,
      size: Math.floor(Math.random() * 1000000) + 500000,
      type: 'image/jpeg'
    }
  }
}

/**
 * 检查是否应该使用模拟API
 */
const shouldUseMockApi = () => {
  const { isMockMode } = require('./config.js')
  return isMockMode()
}

/**
 * 显示模拟模式提示
 */
const showMockModeNotice = () => {
  if (shouldUseMockApi()) {
    console.warn('🔧 当前运行在模拟API模式下')
    console.warn('🔧 如需连接真实服务器，请修改 utils/config.js 中的 isDevelopment 为 false')
  }
}

module.exports = {
  mockRequest,
  mockUpload,
  shouldUseMockApi,
  showMockModeNotice,
  mockApiResponses
}